package com.huayanginfo.saas.member;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.huayanginfo.saas.datasource.ConnectionInfo;
import com.huayanginfo.saas.datasource.ConnectionStrategy;
import com.huayanginfo.saas.domain.member.RegisterCompanyVerify;
import com.huayanginfo.saas.domain.member.SaasLog;
import com.huayanginfo.saas.domain.member.User;

public class RegisterCompanyDao extends HibernateDaoSupport {

	/**
	 * 包括向LDAP中输出公司及用户信息及数据库初始化
	 * 
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public ConnectionInfo saveCompany(User user)
			throws Exception {
		Session session = getSession();
		Transaction transaction = null;
		ConnectionInfo connectionInfo = ConnectionStrategy
		.generateConnectionInfo(user);
		try {
			transaction = session.getTransaction();
			transaction.begin();
			
			SQLQuery query = session.createSQLQuery("{Call saas.create_database(:databaseName, :ip, :username, :password, :firstName, :lastName, :email)}");
			query.setString("databaseName", connectionInfo.getDatabaseName())
			.setString("ip", "localhost")//ConnectionStrategy.getConnectionIp()暂时采用本机做为IP，数据库服务器的IP
			.setString("username", connectionInfo.getUsername());
			query.setString("password", connectionInfo.getPassword())
			.setString("firstName", user.getFirstName())
			.setString("lastName", user.getLastName());
			
			query.setString("email", user.getEmail());
			query.executeUpdate();
			
			SaasLog saasLog = new SaasLog();
			saasLog.setEmail(user.getEmail());
			saasLog.setCompany(user.getCompanyName());
			saasLog.setDbname(connectionInfo.getDatabaseName());
			saasLog.setDbusername("'" + connectionInfo.getUsername() + "'@'" + ConnectionStrategy.getHostIp() + "'");
			session.save(saasLog);
			
			transaction.commit();
			return connectionInfo; 
		} catch (Exception e) {
			if (transaction != null) {
				transaction.rollback();
			}
			throw e;
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	public void persistVerify(RegisterCompanyVerify verify) throws Exception {
		getHibernateTemplate().save(verify);
	}

	@SuppressWarnings("unchecked")
	public List<RegisterCompanyVerify> searchVerify(RegisterCompanyVerify verify) {
		List<RegisterCompanyVerify> results = null;
		Session session = null;
		try {
		session = getSession();
		Criteria criteria = session.createCriteria(RegisterCompanyVerify.class);
		results = criteria.add(Example.create(verify)).list();
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return results;
	}

}
